<?php
namespace app\components;

use yii;
use yii\base\Application;
use yii\base\Behavior;
use yii\web\Response;
use yii\web\View;
use yii\web\Controller;

class BaseBehavior extends Behavior {

    public function events() {
        return [
            Application::EVENT_BEFORE_REQUEST => 'beginRequest',
            Application::EVENT_AFTER_REQUEST => 'afterRequest',
            Controller::EVENT_BEFORE_ACTION => 'beforeAction',
        ];
    }

    public function beginRequest() {
        Yii::setAlias('@web', yii\helpers\Url::base(TRUE));
        Yii::setAlias('@bower', SYS_ROOT . '/modules/bower');
        Yii::$app->urlManager->setBaseUrl(Yii::getAlias('@web'));
        Yii::$app->errorHandler->errorAction = Yii::$app->defaultRoute . "/error";
    }

    public function afterRequest() {
        $data = Yii::$app->response->data;
        if (NULL !== $data && is_array($data)) {
            Yii::$app->response->format = Response::FORMAT_JSON;
        }
    }

    public function beforeAction() {
        //if (NULL === Yii::$app->errorHandler->errorAction) {
            $id = Yii::$app->controller->uniqueId;
            Yii::$app->errorHandler->errorAction = "{$id}/error";
        //}

        //Yii::$app->view->on(View::EVENT_BEFORE_RENDER, [Yii::$app->controller, 'beforeRender']);
        Yii::$app->view->on(View::EVENT_AFTER_RENDER, [$this, 'afterRender']);
    }

    public function afterRender(yii\base\ViewEvent $event) {
        $output = $event->output;
        if (strpos($output, '</html>') === FALSE || strpos($output, '<!-- Generated by') !== FALSE) {
            return;
        }
        $runtime = sprintf('%0.6f', microtime(TRUE) - YII_BEGIN_TIME);
        $memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage(TRUE) / 1024 / 1024, 2) . '[mb]';
        $ip = Yii::$app->request->getUserIP();
        $name = Yii::$app->id;
        $generated = "<!-- Generated by {$name} (memory:{$memory},Processed in {$runtime} second(s),ip:{$ip}) QQ:224327780 -->";
        //$event->output = preg_replace(['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'], ['>', '<', '\\1'], $event->output);
        $event->output = str_replace('</html>', "</html>{$generated}", $event->output);
    }
}